
load('summary_data/fig2.rda')

create_party_plot <- function(data, party_name) {
  
  party_data <- data %>%
    filter(Party == party_name)
  
  party_data %>% 
    ggplot() +
    aes(x = Candidate_Year, y = Percent3 / 100, fill = Wealth_Rank) +
    geom_bar(stat = "identity") +
    
    geom_text(aes(label = paste0(Percent2, "%\n(", Amount, ")")), 
              position = position_stack(vjust = 0.5),
              size = 2, 
              color = if_else(party_data$Wealth_Rank == '[99.9,)', 'white', 'black')) +
    
    labs(title = element_blank(), # paste(party_name, "Candidates"),
         x     = element_blank(), # "Candidate and Year",
         y     = element_blank(), # "Percent",
         fill  = "Wealth Rank") +
    scale_y_continuous(labels = scales::percent) +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 0, hjust = 0.5),
          axis.text   = element_text(face = "bold"),
          plot.title = element_text(hjust = 0.5)) +
    scale_fill_brewer(palette = "Greens")
}

# Create separate plots for Republicans and Democrats
republican_plot <- create_party_plot(cdf, "Republican")
democrat_plot   <- create_party_plot(cdf, "Democratic")

# Combine the plots using patchwork
combined_plot <- republican_plot + democrat_plot +
  plot_layout(ncol = 2) +
  plot_layout(guides = "collect") +
  plot_layout(axes   = "collect")

ggsave('figures/fig2.pdf', plot = combined_plot, width = 7, height = 4)
